package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.EmpPaperContractAddDTO;
import org.jsola.hr.dto.EmpPaperContractUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.EmpPaperContractQuery;
import org.jsola.hr.service.IEmpPaperContractService;
import org.jsola.hr.vo.EmpPaperContractExcelVO;
import org.jsola.hr.vo.EmpPaperContractListVO;
import org.jsola.hr.vo.EmpPaperContractVO;
import org.jsola.hr.vo.HrPaperContractCountVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;


/**
 * 纸质合同
 *
 * @author zhr
 */
@RestController("hrEmpPaperContractController")
@RequestMapping(HrConstants.API_PATH + "/v1/empPaperContracts")
public class EmpPaperContractController implements IEmpPaperContractControllerAPI {

    @Autowired
    private IEmpPaperContractService empPaperContractService;

    @Override
    @PostMapping
    public Result<EmpPaperContractVO> save(@Valid @RequestBody EmpPaperContractAddDTO empPaperContractAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增纸质合同权限校验

        return Result.success(
                empPaperContractService.save(empPaperContractAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody EmpPaperContractUpdateDTO empPaperContractUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改纸质合同权限校验

        int count = empPaperContractService.update(empPaperContractUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }



    @Override
    @DeleteMapping(value = "/{empPaperContractId}")
    public Result<Integer> delete(@PathVariable String empPaperContractId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除纸质合同权限校验

        int count = empPaperContractService.deleteByIds(tokenUser, empPaperContractId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] empPaperContractIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除纸质合同权限校验

        int count = empPaperContractService.deleteByIds(tokenUser, empPaperContractIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{empPaperContractId}")
    public Result<EmpPaperContractVO> findById(@PathVariable String empPaperContractId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看纸质合同权限校验

        return Result.success(
            empPaperContractService.selectById(empPaperContractId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<EmpPaperContractListVO>> listAll(@Valid EmpPaperContractQuery empPaperContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看纸质合同权限校验

        return Result.success(
            empPaperContractService.select(empPaperContractQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<EmpPaperContractListVO>> page(@Valid EmpPaperContractQuery empPaperContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            empPaperContractService.selectPage(empPaperContractQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping("/selectPageByEmpInfo")
    public Result<Page<EmpPaperContractListVO>> selectPageByEmpInfo(@Valid EmpPaperContractQuery empPaperContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empPaperContractService.selectPageByEmpInfo(empPaperContractQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/selectPageByEmpInfoPost")
    public Result<Page<EmpPaperContractListVO>> selectPageByEmpInfoPost(@RequestBody @Valid EmpPaperContractQuery empPaperContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empPaperContractService.selectPageByEmpInfo(empPaperContractQuery, tokenUser)
        );
    }


    @Override
    @PostMapping("/importFile")
    public Result<EmpPaperContractExcelVO> importFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("companyId") String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导入excel权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");

        EmpPaperContractExcelVO empPaperContractExcelVO = empPaperContractService.importFile(excelFile, tokenUser, companyId);
        if (Objects.isNull(empPaperContractExcelVO)) {
            return Result.fail("文件上传失败,请检查上传的模板");
        }

        return Result.success(empPaperContractExcelVO);
    }

    @Override
    @GetMapping("/statisticsCountByCompanyId/{companyId}")
    public Result<HrPaperContractCountVO> statisticsCountByCompanyId(@PathVariable String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empPaperContractService.statisticsCountByCompanyId(companyId, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportPaperContract")
    public ResponseEntity<Resource> exportPaperContract(@RequestBody EmpPaperContractQuery empPaperContractQuery) {
        TokenUser tokenUser = UserContext.getUser();

        empPaperContractQuery.setEnName("contract");
        // todo 查看项目权限校验
        String excelFilePath = empPaperContractService.exportPaperContract(empPaperContractQuery, tokenUser);
        // 导出excel
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8),
                StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

}

